package com.hongyi.modelcontest.core.util;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class AuthCode {
    @Cacheable(value = "PHONE_CODE", key = "#phone")
    public String getCode(String phone) {
        return null;
    }

    @CachePut(value = "PHONE_CODE", key = "#phone")
    public String sendCode(String phone) {
        String code = createNum(4);

        SMSUtils.shouli(phone, code);

        return code;
    }

    @CacheEvict(value = "PHONE_CODE", key = "#phone")
    public String deleteCode(String phone) {

        return null;
    }

    private String createNum(int num) {
        Random random = new Random();
        StringBuilder fourRandom = new StringBuilder(random.nextInt(10000) + "");
        int randLength = fourRandom.length();
        if (randLength < num) {
            for (int i = 1; i <= num - randLength; i++) {
                fourRandom.insert(0, "0");
            }
        }
        return fourRandom.toString();
    }
}
